package com.ych.SDK.alibaba.alipaySDK;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ych.SDK.alibaba.alipaySDK.config.AlipayConfig;
import com.ych.SDK.alibaba.alipaySDK.entity.AlipayQueryOrderInfo_Request;
import com.ych.SDK.alibaba.alipaySDK.entity.AlipayRefundEntity;
import com.ych.modules.base.dbEntity.TUserAccountRechargeOrderEntity;
import com.ych.utils.DateUtils;
import com.ych.utils.UUID;
import org.apache.commons.lang.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2020/12/21
 * Time: 14:24
 * Description:
 */
public class AlipayUtil {
    /**
     * 生成 APP支付订单信息
     */
    public static String createOrder(TUserAccountRechargeOrderEntity order) {
        //实例化客户端
        DefaultAlipayClient alipayClient = initAlipayClient();
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        //拿到订单数据创建支付订单
        model.setBody("云创·汇充值订单支付");
        model.setSubject("云创·汇充值订单支付");
        model.setOutTradeNo(order.getRechargeId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String timeExpire = sdf.format(DateUtils.addDateSeconds(new Date(), 60 * 5));//创建时间+5分钟
        model.setTimeExpire(timeExpire);//绝对超时时间，格式为yyyy-MM-dd HH:mm。 5分钟
//        model.setTimeoutExpress("3m");
        model.setTotalAmount(order.getCashAmount().toString());
        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.notify_url);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            return response.getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 实例化客户端
     *
     * @return
     */
    private static DefaultAlipayClient initAlipayClient() {
        DefaultAlipayClient alipayClient =
                new DefaultAlipayClient(AlipayConfig.server_url,
                        AlipayConfig.appid,
                        AlipayConfig.private_key,
                        AlipayConfig.format,
                        AlipayConfig.charset,
                        AlipayConfig.public_key,
                        AlipayConfig.sign_type);
        return alipayClient;
    }

    /**
     * 退款
     *
     * @param orderEntity 需要退款的订单
     */
    public static boolean refund(AlipayRefundEntity orderEntity) {
        DefaultAlipayClient alipayClient = initAlipayClient();
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        //取出退款数据封装进bizContent
        AlipayTradeRefundModel refundModel = new AlipayTradeRefundModel();
        if (StringUtils.isBlank(orderEntity.getTrade_no())) {
            refundModel.setOutTradeNo(orderEntity.getOut_trade_no());
        } else {
            refundModel.setTradeNo(orderEntity.getTrade_no());
        }
        refundModel.setRefundAmount(orderEntity.getRefund_amount().toPlainString());
        refundModel.setRefundReason(orderEntity.getRefund_reason());
        refundModel.setOutRequestNo(UUID.randomUUID());
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        request.setBizModel(refundModel);
        try {
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                //退款成功  修改数据库
                return true;
            } else {
                //throw new RuntimeException("退款失败！");
                return false;
            }
        } catch (AlipayApiException e) {
            //throw new RuntimeException(e);
            return false;
        }
    }

    /**
     * 查询订单信息
     */
    public static String queryAlipayOrderInfo(AlipayQueryOrderInfo_Request queryOrderInfo) {
        try {
            if (StringUtils.isBlank(queryOrderInfo.getOut_trade_no()) && StringUtils.isBlank(queryOrderInfo.getTrade_no())) {
                throw new RuntimeException("查询条件不能同时为空");
            }
            DefaultAlipayClient alipayClient = initAlipayClient();
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent(JSONObject.toJSONString(queryOrderInfo));
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            return response.getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }
}
